import axios from 'axios'
import ls from './localStorage'
export default {
  async authRequest(options) {
    let accessToken = await this.getToken()
    if (!accessToken) return false
    let header = options.header || {}
    header.Authorization = 'Bearer ' + accessToken
    options.headers = header
    return await this.request(options)
  },
  async request(options) {
    return await axios.request(options)
  },
  async getToken() {
    // 从缓存中取出 Token
    let accessToken = ls.getItem('access_token')
    let expiredAt = ls.getItem('access_token_expired_at')

    // 如果 token 过期了，则调用刷新方法
    if (accessToken && new Date().getTime() > expiredAt) {
      let refreshResponse = await this.refreshToken(accessToken)

      // 刷新成功
      if (refreshResponse.status === 200) {
        return accessToken = refreshResponse.data.access_token
      }
    } else if (accessToken) {
      return accessToken
    }
    // 刷新失败或者没有 Token，重新调用登录方法，设置 Token
    return false
  },
  async refreshToken(accessToken) {
    // 请求刷新接口
    let refreshResponse = await this.request({
      url: '/api/authorizations/current',
      method: 'PUT',
      headers: {
        'Authorization': 'Bearer ' + accessToken
      }
    })

    // 刷新成功状态码为 200
    if (refreshResponse.status === 200) {
      // 将 Token 及过期时间保存在 storage 中
      ls.setItem('access_token', refreshResponse.data.access_token)
      ls.setItem('access_token_expired_at', new Date().getTime() + refreshResponse.data.expires_in * 1000)
    }
    return refreshResponse
  },
  async checkLogined() {
    try {
      return await this.getToken()
    } catch (err) {
      // 刷新失败 说明 token 无效，清除
      ls.removeItem('access_token')
      ls.removeItem('access_token_expired_at')
      return false
    }
  },
  async updateWatchStatus(id, status) {
    let watchResponse = await this.authRequest({
      url: '/api/watch/' + id,
      method: 'PUT',
      data: {
        'status': status
      }
    });
    return watchResponse
  }
}
